<template>
  <el-dialog
    :title="isEdit ? '编辑商品' : '创建商品'"
    :model-value="visible"
    @update:model-value="$emit('update:visible', $event)"
    width="70%"
  >
    <el-form
      ref="formRef"
      :model="localFormData"
      :rules="formRules"
      label-width="100px"
      :disabled="disabled"
    >
      <el-row>
        <el-col :span="8">
          <el-form-item label="商品名称">
            <el-input v-model="localFormData.name" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="商品分区">
            <el-select
              v-model="localFormData.plural"
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="item in partitionList"
                :key="item.id"
                :label="item.pluralName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="商品一级分类">
            <el-select
              v-model="localFormData.commodityClassifyLevel1"
              placeholder="请选择"
            >
              <el-option
                v-for="item in classifyList"
                :key="item.id"
                :label="item.classifyName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="市场价">
            <el-input v-model="localFormData.marketMoney" type="number" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="单价">
            <el-input v-model="localFormData.money" type="number" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="抵扣金额">
            <el-input v-model="localFormData.money1" type="number" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="规格">
            <el-input
              v-model="localFormData.standard"
              placeholder="以 / 分割规格"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="尺码">
            <el-input
              v-model="localFormData.sizes"
              placeholder="以 / 分割尺码"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="型号">
            <el-input
              v-model="localFormData.model"
              placeholder="以 / 分割型号"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="库存">
            <el-input v-model="localFormData.stock" />
          </el-form-item>
        </el-col>
        <el-col :span="8" v-if="isEdit">
          <el-form-item label="销量">
            <el-input v-model="localFormData.sales" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="商户手机号">
            <el-input v-model="localFormData.merchantMobile" />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8">
          <el-form-item label="赠送积分">
            <el-input v-model="localFormData.gainIntegral" />
          </el-form-item>
        </el-col> -->
        <!-- <el-col :span="8">
          <el-form-item label="利润">
            <el-input v-model="localFormData.profitMoney" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="贡献点">
            <el-input v-model="localFormData.gainValue" />
          </el-form-item>
        </el-col> -->
        <el-col :span="8">
          <el-form-item label="是否推荐">
            <el-radio-group v-model="localFormData.isTj">
              <el-radio :label="1">推荐</el-radio>
              <el-radio :label="0">不推荐</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="精选爆品">
            <el-radio-group v-model="localFormData.isBp">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="品牌特卖">
            <el-radio-group v-model="localFormData.isTm">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="本周主打">
            <el-radio-group v-model="localFormData.isZd">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="甄选好物">
            <el-radio-group v-model="localFormData.isZx">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="是否限购">
            <el-radio-group v-model="localFormData.isQuota">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="让利比率" prop="offerDiscountsRatio">
            <el-select
              v-model="localFormData.offerDiscountsRatio"
              placeholder="请选择让利比率"
              clearable
            >
              <el-option
                v-for="item in discountRatioOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="商品图片">
            <div class="crop-demo">
              <img
                v-if="localFormData.showPic"
                :src="localFormData.showPic"
                class="pre-img"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              <input
                class="crop-input"
                type="file"
                name="image"
                accept="image/*"
                @change="handleImageUpload($event, 'showPic')"
                :disabled="disabled"
              />
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="展示图片">
            <div class="crop">
              <div class="crop-demo">
                <img
                  v-if="localFormData.showDetails1"
                  :src="localFormData.showDetails1"
                  class="pre-img"
                />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                <input
                  class="crop-input"
                  type="file"
                  name="image"
                  accept="image/*"
                  @change="handleImageUpload($event, 'showDetails1')"
                  :disabled="disabled"
                />
              </div>
              <div class="crop-demo">
                <img
                  v-if="localFormData.showDetails2"
                  :src="localFormData.showDetails2"
                  class="pre-img"
                />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                <input
                  class="crop-input"
                  type="file"
                  name="image"
                  accept="image/*"
                  @change="handleImageUpload($event, 'showDetails2')"
                  :disabled="disabled"
                />
              </div>
              <div class="crop-demo">
                <img
                  v-if="localFormData.showDetails3"
                  :src="localFormData.showDetails3"
                  class="pre-img"
                />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                <input
                  class="crop-input"
                  type="file"
                  name="image"
                  accept="image/*"
                  @change="handleImageUpload($event, 'showDetails3')"
                  :disabled="disabled"
                />
              </div>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="详情">
        <Tinymce-editor
          :disabled="disabled"
          :value="localFormData.contextDetails"
          @input="(res) => (localFormData.contextDetails = res)"
        />
      </el-form-item>
      <el-form-item label="说明">
        <el-input
          type="textarea"
          placeholder="请输入内容"
          v-model="localFormData.explains"
          show-word-limit
          :rows="12"
          resize="none"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="handleConfirm">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ossUpload } from "../../../api/index";
import TinymceEditor from "../../../components/tinymce-editor";

export default {
  name: "CommodityDialog",
  components: { TinymceEditor },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    formData: {
      type: Object,
      default: () => ({}),
    },
    isEdit: {
      type: Boolean,
      default: false,
    },
    partitionList: {
      type: Array,
      default: () => [],
    },
    classifyList: {
      type: Array,
      default: () => [],
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    merchantId: {
      type: String,
      default: "10",
    },
  },
  emits: ["update:visible", "confirm"],
  data() {
    return {
      localFormData: {},
      // 让利比率选项 3%-20%
      discountRatioOptions: [
        { label: "3%", value: 0.03 },
        { label: "4%", value: 0.04 },
        { label: "5%", value: 0.05 },
        { label: "6%", value: 0.06 },
        { label: "7%", value: 0.07 },
        { label: "8%", value: 0.08 },
        { label: "9%", value: 0.09 },
        { label: "10%", value: 0.1 },
        { label: "11%", value: 0.11 },
        { label: "12%", value: 0.12 },
        { label: "13%", value: 0.13 },
        { label: "14%", value: 0.14 },
        { label: "15%", value: 0.15 },
        { label: "16%", value: 0.16 },
        { label: "17%", value: 0.17 },
        { label: "18%", value: 0.18 },
        { label: "19%", value: 0.19 },
        { label: "20%", value: 0.2 },
      ],
      // 表单验证规则
      formRules: {
        offerDiscountsRatio: [
          { required: true, message: "请选择让利比率", trigger: "change" },
        ],
      },
    };
  },
  watch: {
    formData: {
      handler(val) {
        // 只有在对话框打开时才更新 localFormData
        if (this.visible) {
          this.localFormData = { ...val };
        }
      },
      immediate: true,
      deep: true,
    },
    visible: {
      handler(val) {
        // 对话框打开时，同步 formData 到 localFormData
        if (val) {
          this.localFormData = { ...this.formData };
          // 重置表单验证
          this.$nextTick(() => {
            if (this.$refs.formRef) {
              this.$refs.formRef.clearValidate();
            }
          });
        } else if (!val) {
          // 对话框关闭后，延迟清空数据和验证，避免 DOM 操作错误
          setTimeout(() => {
            this.localFormData = {};
            if (this.$refs.formRef) {
              this.$refs.formRef.clearValidate();
            }
          }, 300);
        }
      },
    },
  },
  methods: {
    // 统一的图片上传处理
    handleImageUpload(event, field) {
      let imgFile = event.target.files[0];
      if (!imgFile) return;

      let formData = new FormData();
      formData.append("file", imgFile);
      ossUpload(formData).then((res) => {
        this.localFormData[field] = res.data;
      });
    },
    handleCancel() {
      this.$emit("update:visible", false);
    },
    handleConfirm() {
      // 验证表单
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.$emit("confirm", {
            ...this.localFormData,
            merchantId: this.merchantId,
          });
        } else {
          this.$message.error("请填写必填项");
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.crop {
  display: flex;
  align-items: center;
}

.crop-demo {
  display: flex;
  align-items: flex-end;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  width: 148px;
  height: 148px;
  margin-right: 5px;
  position: relative;

  .pre-img {
    width: 146px;
    height: 146px;
    background: #f8f8f8;
    border: 1px solid #eee;
    border-radius: 5px;
    object-fit: cover;
  }

  .crop-input {
    position: absolute;
    width: 148px;
    height: 148px;
    left: 0px;
    top: 0px;
    opacity: 0;
    cursor: pointer;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 148px;
    height: 148px;
    line-height: 148px;
    text-align: center;
  }
}
</style>
